package worker

import (
	"context"
	api "dfs/server/master/api/worker"
	"fmt"
	"math/rand"
	"time"
)

type Worker struct {
	ID        string
	Cap       int
	Timestamp int64
}

var workers map[string]Worker

func Init() {
	if workers == nil {
		workers = make(map[string]Worker)
	}
	for k := range workers {
		delete(workers, k)
	}
	fmt.Println("[ResourceManager]已初始化Worker队列")
}

func RandomWorker() string {
	var available []string
	for _, worker := range workers {
		if worker.Cap != 0 {
			available = append(available, worker.ID)
		}
	}
	return available[rand.Intn(len(available))]
}

func Scan(gap int, stop <-chan struct{}) {
	for {
		now := time.Now().Unix()
		select {
		case <-stop:
			fmt.Println("[ResourceManager]Worker队列监听已关闭")
		default:
			for id, worker := range workers {
				if now-worker.Timestamp > 10 {
					delete(workers, id)
					fmt.Printf("[ResourceManager]节点Worker@%s心跳已过期\n", id)
				}
			}
			time.Sleep(time.Duration(gap) * time.Second)
		}
	}
}

type WorkerService struct{}

func (w *WorkerService) HeartBeat(ctx context.Context, req *api.HeartBeatReq) (*api.HeartBeatResp, error) {
	worker, ok := workers[req.Id]
	if ok {
		worker.Cap = int(req.Cap)
		worker.Timestamp = time.Now().Unix()
	} else {
		worker = Worker{
			ID:        req.Id,
			Cap:       int(req.Cap),
			Timestamp: time.Now().Unix(),
		}
		fmt.Printf("Worker节点@%s加入集群\n", req.Id)
	}
	workers[req.Id] = worker
	return &api.HeartBeatResp{Success: true, Message: "发送心跳成功"}, nil
}
